package model

import (
	"../encode"
	"../global"
	"github.com/go-pg/pg"
)

type AdminModel struct{}

//新增管理员模型
func (*AdminModel) RegAdmin(query *Admin) (err error) {
	query.Password, err = encode.MD5ByStr(query.Password, global.Config.Section("app").Key("passwordKey").String())
	if err != nil {
		return
	}
	_, err = global.DB.Model(query).Insert()
	return
}

//查询管理员模型
func (*AdminModel) GetAdmin(query *Admin, column []string, listParams *ListParams) (result []Admin, err error) {
	model := global.DB.Model(&result)
	for k := range column {
		model.Column(column[k])
	}

	if query.ID != 0 {
		model.Where("id=?", query.ID)
	}

	if query.Name != "" {
		model.Where("name=?", query.Name)
	}
	if query.Mobile != "" {
		model.Where("mobile=?", query.Mobile)
	}
	if query.Email != "" {
		model.Where("email=?", query.Email)
	}

	if listParams.Limit != 0 && listParams.Page != 0 {
		err = model.Limit(listParams.Limit).Offset((listParams.Page - 1) * listParams.Limit).Select()
	} else {
		err = model.Limit(listParams.Limit).Select()
	}
	return
}

//修改管理员资料模型
func (*AdminModel) EditAdmin(query *Admin) (err error) {
	model := global.DB.Model(&Admin{})
	model.Where("id=?", query.ID)

	if query.Mobile != "" {
		model.Set("mobile=?", query.Mobile)
	}
	if query.Password != "" {
		query.Password, err = encode.MD5ByStr(query.Password, global.Config.Section("app").Key("passwordKey").String())
		if err != nil {
			return
		}
		model.Set("password=?", query.Password)
	}
	if query.Email != "" {
		model.Set("email=?", query.Email)
	}
	if query.Name != "" {
		model.Set("name=?", query.Name)
	}

	_, err = model.Update()

	return
}

//删除管理员模型
func (*AdminModel) DelAdmin(IDs []int64) (err error) {
	if len(IDs) > 1 {
		_, err = global.DB.Model(&Admin{}).WhereIn("id in (?)", pg.In(IDs)).Delete()
	} else {
		_, err = global.DB.Model(&Admin{}).Where("id=?", IDs[0]).Delete()
	}
	return
}
